package cn.kent.controller;

import cn.kent.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 模拟用户登录
     * 同时返回了sessionId，作为Cookie
     */
    @RequestMapping("/login")
    public String login(HttpSession session) {
        User user = new User(1, "张三", "123456");
        session.setAttribute("currentUser", user);
        System.out.println(session.getId());

        /**************************/
        ServletContext servletContext = session.getServletContext();
        // 模拟存储用户session信息到数据库，用application模拟
        servletContext.setAttribute(String.valueOf(user.getId()), session.getId()); // key-val 用户id-sessionId
        /**************************/

        return "success";
    }

    /**
     * 获取当前用户信息
     * 访问的时候会携带上cookie里的sessionId，去查询指定的session信息
     */
    @RequestMapping("/getUserInfo")
    public User getUserInfo(HttpSession session){
        return (User) session.getAttribute("currentUser");
    }


}
